package october;

/*
I need a function that takes the name of the movie to look up and
the width of the letter grid, and computes the key presses that
will enter that string on the DVR grid. The output should be a
string, with "u", "d", "l", "r", and "!" corresponding to up,
down, left, right, and select.

For example, with a grid of width 5,
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
z
the movie "up" would be "dddd!u!".
 */
public class MovieTitleSelector {
    public static void main(String[] args) {
        int screenWidth = 7;
        printTheScreen(screenWidth);
        String movieTitle = "avatar";
        System.out.println(movieTitle + " : " + getCommandsForMovie(movieTitle, screenWidth));
    }

    private static String getCommandsForMovie(String movieTitle, int screenWidth) {
        StringBuilder result = new StringBuilder();
        char prevChar = 'a';
        for (char c : movieTitle.toCharArray()) {
            int horizDiff = (c - prevChar) % screenWidth;
            int vertDiff = (c - prevChar) / screenWidth;

            if (horizDiff < 0) addDirections(result, 'L', -horizDiff);
            if (horizDiff > 0) addDirections(result, 'R', horizDiff);

            if (vertDiff < 0) addDirections(result, 'U', -vertDiff);
            if (vertDiff > 0) addDirections(result, 'D', vertDiff);
            prevChar = c;
            result.append("!");
        }
        return result.toString();
    }

    private static void addDirections(StringBuilder sb, char direction, int amount) {
        for (int i = 0; i < amount; i++) sb.append(direction);
    }

    private static void printTheScreen(int screenWidth) {
        char currentChar = 'a';
        int linePosition = 0;
        while (currentChar <= 'z') {
            System.out.print(currentChar + " ");
            currentChar++;
            linePosition++;
            if (linePosition == screenWidth) {
                System.out.println();
                linePosition = 0;
            }
        }
        System.out.println();
    }
}
